package operacionesWebAPI;

import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.JSONValue;
import org.json.simple.parser.ContainerFactory;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;

import entidades.Partida;
import entidades.Player;

public class FuncionesJSON {
	public static void f1() {
		JSONParser parser = new JSONParser();

		try {

			Object obj = parser.parse(new FileReader("test.json"));

			JSONObject jsonObject = (JSONObject) obj;

			String name = (String) jsonObject.get("name");
			System.out.println(name);

			long age = (Long) jsonObject.get("age");
			System.out.println(age);

			// loop array
			JSONArray msg = (JSONArray) jsonObject.get("messages");
			Iterator<String> iterator = msg.iterator();
			while (iterator.hasNext()) {
				System.out.println(iterator.next());
			}

		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (ParseException e) {
			e.printStackTrace();
		}
	}

	public static void f2() {
		JSONParser parser = new JSONParser();

		try {

			Object root = parser.parse(new FileReader("ultimas100"));

			JSONObject jsonRoot = (JSONObject) root;

			JSONObject results = (JSONObject) jsonRoot.get("result");

			JSONArray matches = (JSONArray) results.get("matches");

			for (Object o : matches) {
				JSONObject match = (JSONObject) o;

				Long matchID = (Long) match.get("match_id");

				System.out.println(matchID);
			}
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (ParseException e) {
			e.printStackTrace();
		}
	}

	/**
	 * Obtiene las ultimos 100 partidas
	 * 
	 * @param ultimoMatch
	 *            Si no es vacio sirve para comprobar si hemos llegado a la
	 *            ultima partida almacenada
	 * */
	public static ArrayList<Partida> obtenerMatchesID(Long ultimoMatch) {
		ArrayList<Partida> res = new ArrayList<Partida>();
		int salirBucle = 0;
		long startTime = 0;
		Long ultimoMatchObtenido = 0L;
		Long matchSequence = 0L;

		/* Obtener las ultimas 100 partidas y rellenar el fichero 'ultimas100' */
		LlamadasAPI.ultimas100Partidas();

		/* Inicializar el parser */
		JSONParser parser = new JSONParser();

		try {

			Object root = parser.parse(new FileReader("ultimas100"));
			JSONObject jsonRoot = (JSONObject) root;
			JSONObject results = (JSONObject) jsonRoot.get("result");

			/* Comprobar que el resultado no ha sido vacio (result != 0) */
			long numResults = (Long) results.get("num_results");

			while (numResults > 1 && salirBucle == 0) {

				JSONArray matches = (JSONArray) results.get("matches");

				for (Object o : matches) {
					JSONObject match = (JSONObject) o;

					ultimoMatchObtenido = (Long) match.get("match_id");
					startTime = (Long) match.get("start_time");
					matchSequence = (Long)match.get("match_seq_num");

					if (ultimoMatchObtenido.equals(ultimoMatch)) {
						salirBucle = 1;
						break;
					}

					Partida toAdd = new Partida(ultimoMatchObtenido);
					if (!res.contains(toAdd))
						res.add(toAdd);

					System.out.println(matchSequence);
					System.out.println(ultimoMatchObtenido);
				}

				// LlamadasAPI.siguientes100Partidas(res.get(res.size() -
				// 1).getMatchID());

				//LlamadasAPI.siguientes100PartidasStartTime(startTime);
				
				//LlamadasAPI.siguientes100PartidasSequence(matchSequence);
				
				LlamadasAPI.siguientes100Partidas(ultimoMatchObtenido);

				root = parser.parse(new FileReader("ultimas100"));
				jsonRoot = (JSONObject) root;
				results = (JSONObject) jsonRoot.get("result");

				numResults = (Long) results.get("num_results");
			}
			System.out.println();

		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (ParseException e) {
			e.printStackTrace();
		}

		return res;
	}

	public static ArrayList<Partida> completarInformacionPartidas(
			ArrayList<Partida> partidas) {
		ArrayList<Partida> res = new ArrayList<Partida>();

		/* Inicializar el parser */
		JSONParser parser = new JSONParser();

		Object root;
		JSONObject jsonRoot;
		JSONObject results;

		// Recorre todas las partidas
		for (Partida p : partidas) {
			// System.out.println("Buscando la informacion de: " +
			// p.getMatchID() + " . . .");

			// Para cada partida rellena el archivo 'infoPartida' con los datos
			// devueltos por la API
			
			System.out.println("busca info de la partida");
			LlamadasAPI.informacionPartida(p.getMatchID());
			System.out.println("llamada a finalizado");

			try {
				// Leer archivo
				root = parser.parse(new FileReader("infoPartida"));
				jsonRoot = (JSONObject) root;
				results = (JSONObject) jsonRoot.get("result");

				// Datos del objeto partida
				p.setGameMode((Long) results.get("game_mode"));
				p.setRadiantWin((Boolean) results.get("radiant_win"));
				p.setDuration((Long) results.get("duration"));

				// Obtener el array de jugadores
				JSONArray players = (JSONArray) results.get("players");

				// Recorrer el array players
				for (Object o : players) {
					JSONObject player = (JSONObject) o;

					Player aux = new Player();

					if ((Long) player.get("account_id") == null) {
						aux.setPlayerID(4294967295L);
					} else {
						aux.setPlayerID((Long) player.get("account_id"));
					}

					aux.setAssists((Long) player.get("assists"));
					aux.setDeaths((Long) player.get("deaths"));
					aux.setDenies((Long) player.get("denies"));
					aux.setGold((Long) player.get("gold"));
					aux.setGold_per_min((Long) player.get("gold_per_min"));
					aux.setHeroID((Long) player.get("hero_id"));
					aux.setItem0((Long) player.get("item_0"));
					aux.setItem1((Long) player.get("item_1"));
					aux.setItem2((Long) player.get("item_2"));
					aux.setItem3((Long) player.get("item_3"));
					aux.setItem4((Long) player.get("item_4"));
					aux.setItem5((Long) player.get("item_5"));
					aux.setKills((Long) player.get("kills"));
					aux.setLastHits((Long) player.get("last_hits"));
					aux.setLevel((Long) player.get("level"));
					aux.setXp_per_min((Long) player.get("xp_per_min"));
					aux.setSlot((Long) player.get("player_slot"));

					// Añadir el nuevo jugador a la partida
					p.addPlayer(aux);
				}

				// System.out.println("Numero de jugadores: " +
				// p.getPlayers().size());

				res.add(p);

			} catch (FileNotFoundException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			} catch (ParseException e) {
				e.printStackTrace();
			}

		}

		return res;
	}

	public static HashMap<Long, ArrayList<String>> getHeroesJSON() {
		HashMap<Long, ArrayList<String>> res = new HashMap<Long, ArrayList<String>>();

		// Rellenar el archivo 'heroes'
		LlamadasAPI.getHeroesAPI();

		/* Inicializar el parser */
		JSONParser parser = new JSONParser();

		try {

			Object root = parser.parse(new FileReader("heroes"));
			JSONObject jsonRoot = (JSONObject) root;
			JSONObject results = (JSONObject) jsonRoot.get("result");

			JSONArray heroes = (JSONArray) results.get("heroes");

			for (Object o : heroes) {
				ArrayList<String> aux = new ArrayList<String>();
				JSONObject heroe = (JSONObject) o;

				Long id = (Long) heroe.get("id");
				String name = (String) heroe.get("name");
				String localized_name = (String) heroe.get("localized_name");

				aux.add(name);
				aux.add(localized_name);

				res.put(id, aux);
			}

		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (ParseException e) {
			e.printStackTrace();
		}

		return res;
	}

	public static HashMap<Long, ArrayList<String>> getItemsJSON() {
		HashMap<Long, ArrayList<String>> res = new HashMap<Long, ArrayList<String>>();

		// Rellenar el archivo 'items'
		LlamadasAPI.getItemsAPI();

		/* Inicializar el parser */
		JSONParser parser = new JSONParser();

		ContainerFactory containerFactory = new ContainerFactory() {
			public List creatArrayContainer() {
				return new LinkedList();
			}

			public Map createObjectContainer() {
				return new LinkedHashMap();
			}

		};

		try {

			Object root = parser.parse(new FileReader("items"));
			JSONObject jsonRoot = (JSONObject) root;
			JSONObject results = (JSONObject) jsonRoot.get("itemdata");
			
			JSONObject item;
			
			for(Object key : results.keySet()){
				String s = key.toString();
				ArrayList<String> aux = new ArrayList<String>();
				
				item = (JSONObject) results.get(s);
				
				Long id = (Long) item.get("id");
				String img = (String) item.get("img");
				String dname = (String) item.get("dname");

				aux.add(img);
				aux.add(dname);

				res.put(id, aux);
				
			}

		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (ParseException e) {
			e.printStackTrace();
		}

		return res;
	}

}
